package com.example.demo.service;

import com.example.demo.model.ReceivingAddress;
import com.example.demo.mapper.ReceivingAddressMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ReceivingAddressService {
    
    @Autowired
    private ReceivingAddressMapper addressMapper;
    
    @Transactional
    public boolean addAddress(ReceivingAddress address) {
        // 如果设置为默认地址，先将其他地址设为非默认
        if (address.getIsDefault() == 1) {
            addressMapper.clearDefault(address.getUserId());
        }
        return addressMapper.insert(address) > 0;
    }
    
    public List<ReceivingAddress> getUserAddresses(Integer userId) {
        return addressMapper.selectByUserId(userId);
    }
    
    public ReceivingAddress getDefaultAddress(Integer userId) {
        return addressMapper.selectDefaultAddress(userId);
    }
    
    @Transactional
    public boolean updateAddress(ReceivingAddress address) {
        // 如果设置为默认地址，先将其他地址设为非默认
        if (address.getIsDefault() == 1) {
            addressMapper.clearDefault(address.getUserId());
        }
        return addressMapper.update(address) > 0;
    }
    
    public boolean deleteAddress(Integer id) {
        return addressMapper.delete(id) > 0;
    }
} 